package com.pengcheng.taskapplication.mvp.view.activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.provider.Settings;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.pengcheng.taskapplication.R;
import com.pengcheng.taskapplication.contants.ConstantValue;
import com.pengcheng.taskapplication.helper.ImageLoader;
import com.pengcheng.taskapplication.model.BannerModel;
import com.pengcheng.taskapplication.model.CheckModel;
import com.pengcheng.taskapplication.model.SmsModel;
import com.pengcheng.taskapplication.model.SubscribeOrderListModel;
import com.pengcheng.taskapplication.model.UserDetailVo;
import com.pengcheng.taskapplication.model.WalletModel;
import com.pengcheng.taskapplication.mvp.presenter.UserPresenter;
import com.pengcheng.taskapplication.net.IView;
import com.pengcheng.taskapplication.util.DisplayHelper;
import com.pengcheng.taskapplication.util.SPUtils;
import com.pengcheng.taskapplication.util.ToastUtils;
import com.pgyersdk.update.DownloadFileListener;
import com.pgyersdk.update.PgyUpdateManager;
import com.pgyersdk.update.UpdateManagerListener;
import com.pgyersdk.update.javabean.AppBean;
import com.sina.weibo.sdk.constant.WBConstants;
import com.squareup.picasso.Picasso;
import com.yanzhenjie.permission.Action;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.Permission;
import com.zhouwei.mzbanner.MZBannerView;
import com.zhouwei.mzbanner.holder.MZHolderCreator;
import com.zhouwei.mzbanner.holder.MZViewHolder;

import java.io.File;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by ZFT on 2020/10/25.
 */

public class IndexActivity extends BaseActivity implements IView{
    private static final int REQUEST_CODE_READ_EXTERNAL_STORAGE_PERMISSIONS = 1;
    private static final int REQUEST_CODE_WRITE_EXTERNAL_STORAGE = 2;
    private int page=1;
    private int size=10;

    @BindView(R.id.my_banner)
    MZBannerView mMZBannerView;

    @BindView(R.id.top_banner)
    MZBannerView topZannerView;
    public String token;

    @BindView(R.id.img_scan)
    ImageView img_scan;

    private UserDetailVo userDetailVo;
    private int REQUEST_CODE_SCAN = 111;
    List<BannerModel> bannerModels=new ArrayList<>();
    private UserPresenter userPresenter;
    private long from;

    @Override
    protected int layoutResID() {
        return R.layout.activity_index_layout;
    }

    @Override
    protected void initData() {
        userPresenter=new UserPresenter(this);
        token= SPUtils.getString(context, ConstantValue.SpType.token);
        for(int i=0;i<2;i++){
            BannerModel model =new BannerModel();
            model.setImgUrl("https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1603653560349&di=0fe374359299ae43c5c1aa5120d4ab37&imgtype=0&src=http%3A%2F%2Fa0.att.hudong.com%2F56%2F12%2F01300000164151121576126282411.jpg");
            bannerModels.add(model);
        }
        initSize();
        setBanner(bannerModels);
        setTopBanner(bannerModels);
        requestGranted();
        checkUpate();
    }
    public void initSize(){
        double height = DisplayHelper.getDisplayMetrics(context).widthPixels / (750 / 670.0);
		ViewGroup.LayoutParams params = topZannerView.getLayoutParams();
		params.height = (int) (height);
        topZannerView.setLayoutParams(params);
    }

    public void requestGranted(){
        //动态请求权限
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                requestPermissions(
                        new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
                        REQUEST_CODE_READ_EXTERNAL_STORAGE_PERMISSIONS);
                requestPermissions(
                        new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                        REQUEST_CODE_WRITE_EXTERNAL_STORAGE);
            }
        }
    }

    @Override
    public void onSuccess(String code, String msg, Object data, String actionType) {
        if(actionType.equals(ConstantValue.RequestKey.getSubscribes)){
            ArrayList<SubscribeOrderListModel> list= (ArrayList<SubscribeOrderListModel>)data;
            if(list.size()==0){
                Intent intent = new Intent(context, Html5AgressActivity.class);
                intent.putExtra("url","file:///android_asset/instructions.html");
                intent.putExtra("title","办理须知");
                startActivity(intent);
            }else{
                Intent intent =new Intent(context,ApplyListActivity.class);
                intent.putExtra("from",0);
                startActivity(intent);
            }
        }
        if(actionType.equals(ConstantValue.RequestKey.checkCert)){
            CheckModel model=(CheckModel)data;
            if(model.getCertId()==-1){
                Intent intent =new Intent(context,UploadIdCard.class);
                intent.putExtra("from",from);
                intent.putExtra("flag",0l);
                intent.putExtra("certId",model.getCertId());
                startActivity(intent);
            }else if(model.getCertId()>0&!model.isFrontOcrFlag()&!model.isBackOcrFlag()){
                Intent intent =new Intent(context,UploadIdCard.class);
                intent.putExtra("certId",model.getCertId());
                //flag为1的时候，需要回显，重新认证
                intent.putExtra("flag",1l);
                intent.putExtra("from",from);
                startActivity(intent);
            }else {
                //用户是否开卡
                if(userDetailVo!=null) {
                    //未开卡
                    if (!userDetailVo.isHasIcbcAuth()) {
                            //
                        //到绑卡页面
                        Intent intent = new Intent(context, BindCardActivity.class);
                        intent.putExtra("from",from);
                        intent.putExtra("certId",model.getCertId());
                        startActivity(intent);
                    } else {
                        //已经开卡

                        if(from==0) {
//                            Intent intent = new Intent(context, Html5AgressActivity.class);
//                            intent.putExtra("url","file:///android_asset/instructions.html");
//                            intent.putExtra("title","办理须知");
//                            startActivity(intent);
                            getSubscribes(page,size);

                        }else {
                            Intent intent = new Intent(context, MyBankList.class);
                            startActivity(intent);
                        }
                    }
                }

            }
        }
        if(actionType.equals(ConstantValue.RequestKey.userinfo)){
            userDetailVo=(UserDetailVo)data;
            if(userDetailVo!=null){
                SPUtils.putString(context,ConstantValue.SpType.phone,userDetailVo.getCellphone());
            }
        }
    }

    @Override
    public void onFailed(String code, String msg) {

    }

    private void setTopBanner(List<BannerModel> banners){
        topZannerView.addPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                //Log.e("zw","onPageScrolled---->"+position);
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        topZannerView.setPages(banners, new MZHolderCreator<TopBannerViewHolder>() {
            @Override
            public TopBannerViewHolder createViewHolder() {
                return new TopBannerViewHolder();
            }
        });

        topZannerView.start();
        topZannerView.setIndicatorVisible(true);

    }

    public  class TopBannerViewHolder implements MZViewHolder<BannerModel> {
        private ImageView mImageView;
        @Override
        public View createView(Context context) {
            View view = LayoutInflater.from(context).inflate(R.layout.banner_item_layout,null);
            mImageView = (ImageView) view.findViewById(R.id.banner_img);
            mImageView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    from=0;
                    if(check(token)){
                        checkOcr();
                    }
                }
            });
            return view;
        }

        @Override
        public void onBind(Context context, int i, BannerModel bannerModel) {
            Log.e("zhouwei","current position:"+i);
            ImageLoader.displayImage(context,R.drawable.index_top,mImageView);
            mImageView.setTag(bannerModel);
        }
    }

    private void setBanner(List<BannerModel> banners){
        mMZBannerView.addPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                //Log.e("zw","onPageScrolled---->"+position);
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        mMZBannerView.setPages(banners, new MZHolderCreator<BannerViewHolder>() {
            @Override
            public BannerViewHolder createViewHolder() {
                return new BannerViewHolder();
            }
        });

        mMZBannerView.start();
        mMZBannerView.setIndicatorVisible(false);

    }
    public static class BannerViewHolder implements MZViewHolder<BannerModel> {
        private ImageView mImageView;
        @Override
        public View createView(Context context) {
            View view = LayoutInflater.from(context).inflate(R.layout.activity_plate_item_layout,null);
            mImageView = (ImageView) view.findViewById(R.id.imgPlate);
            return view;
        }

        @Override
        public void onBind(Context context, int i, BannerModel bannerModel) {
            Log.e("zhouwei","current position:"+i);
            Picasso.with(context).load(bannerModel.getImgUrl()).into(mImageView);
        }
    }

    @OnClick({R.id.img_scan,R.id.ll_dzcp,R.id.ll_wdqb})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.img_scan:
                AndPermission.with(this)
                        .permission(Permission.CAMERA, Permission.READ_EXTERNAL_STORAGE)
                        .onGranted(new Action() {
                            @Override
                            public void onAction(List<String> permissions) {

                            }
                        })
                        .onDenied(new Action() {
                            @Override
                            public void onAction(List<String> permissions) {
                                Uri packageURI = Uri.parse("package:" + getPackageName());
                                Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, packageURI);
                                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

                                startActivity(intent);

                                Toast.makeText(context, "没有权限无法扫描呦", Toast.LENGTH_LONG).show();
                            }
                        }).start();
                break;
                case R.id.ll_dzcp:
                    from=0;
                    if(check(token)){
                        checkOcr();
                    }
                break;
                case R.id.ll_wdqb:
                    from=1;
                    if(check(token)){
                        checkOcr();
                    }
                    break;
        }
    }


    public boolean check(String token){
        if(token==null||token.length()==0){
            Intent intent =new Intent(context,LoginActivity.class);
            intent.putExtra("from",from);
            startActivity(intent);
            return false;
        }else {
            return true;
        }
    };

    @Override
    protected void onResume() {
        super.onResume();
        token=SPUtils.getString(context,ConstantValue.SpType.token);
        getUserDetail();

    }

    public void checkOcr(){
        userPresenter.checkCert(ConstantValue.RequestKey.checkCert);
    }
    public void checkList(){
        userPresenter.checkCert(ConstantValue.RequestKey.checkList);
    }
    public void getSubscribes(int page,int pageSize){
        userPresenter.getSubscribes(page,pageSize,ConstantValue.RequestKey.getSubscribes);
    }

    public void getUserDetail(){
        userPresenter.getUserDetail(ConstantValue.RequestKey.userinfo);
    }

    public void checkUpate(){
        /** 新版本 **/

        new PgyUpdateManager.Builder()
                .setForced(true)                //设置是否强制更新,非自定义回调更新接口此方法有用
                .setUserCanRetry(false)         //失败后是否提示重新下载，非自定义下载 apk 回调此方法有用
                .setDeleteHistroyApk(false)     // 检查更新前是否删除本地历史 Apk
                .setUpdateManagerListener(new UpdateManagerListener() {
                    @Override
                    public void onNoUpdateAvailable() {
                        //没有更新是回调此方法
                        Log.d("pgyer", "there is no new version");
                    }

                    @Override
                    public void onUpdateAvailable(AppBean appBean) {
                        //没有更新是回调此方法
                        Log.d("pgyer", "there is new version can update"
                                + "new versionCode is " + appBean.getVersionCode());

                        //调用以下方法，DownloadFileListener 才有效；如果完全使用自己的下载方法，不需要设置DownloadFileListener
                        PgyUpdateManager.downLoadApk(appBean.getDownloadURL());
                    }

                    @Override
                    public void checkUpdateFailed(Exception e) {
                        //更新检测失败回调
                        Log.e("pgyer", "check update failed ", e);

                    }
                })
                //注意 ：下载方法调用 PgyUpdateManager.downLoadApk(appBean.getDownloadURL()); 此回调才有效
                .setDownloadFileListener(new DownloadFileListener() {   // 使用蒲公英提供的下载方法，这个接口才有效。
                    @Override
                    public void downloadFailed() {
                        //下载失败
                        Log.e("pgyer", "download apk failed");
                    }

                    @Override
                    public void downloadSuccessful(File file) {
                        Log.e("pgyer", "download apk failed");
                        PgyUpdateManager.installApk(file);  // 使用蒲公英提供的安装方法提示用户 安装apk

                    }

                    @Override
                    public void onProgressUpdate(Integer... integers) {
                        Log.e("pgyer", "update download apk progress : " + integers[0]);
                    }
                })
                .register();
    }


    @SuppressLint("NewApi")
    @Override
    public void onRequestPermissionsResult(int requestCode,
                                           String[] permissions, int[] grantResults) {
        switch (requestCode) {
            case REQUEST_CODE_WRITE_EXTERNAL_STORAGE: {
                for (int i = 0; i < permissions.length; i++) {
                    if (grantResults[i] == PackageManager.PERMISSION_GRANTED) {
                        //Toast.makeText(this, "允许写存储！", Toast.LENGTH_SHORT).show();
                    } else {
                        Toast.makeText(this, "未允许写存储！", Toast.LENGTH_SHORT).show();
                    }

                }
            }
            case REQUEST_CODE_READ_EXTERNAL_STORAGE_PERMISSIONS: {
                for (int i = 0; i < permissions.length; i++) {
                    if (grantResults[i] == PackageManager.PERMISSION_GRANTED) {
                        //Toast.makeText(this, "允许读存储！", Toast.LENGTH_SHORT).show();
                    } else {
                        Toast.makeText(this, "未允许读存储！", Toast.LENGTH_SHORT).show();
                    }

                }
            }
            break;
            default: {
                super.onRequestPermissionsResult(requestCode, permissions,
                        grantResults);
            }
        }
    }

}
